import axios from "axios";
import router from "@/router";
import store from '@/store'

let checkISLogin = (userInfo) => {
    return userInfo.userid !== ''
}

//清除cookie
let clearCookie = () => {
    let keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
        for (let i = keys.length; i--;) {
            document.cookie = keys[i] + '=0;path=/;expires=' + new Date(0).toUTCString();//清除当前域名下的,例如：m.kevis.com
            document.cookie = keys[i] + '=0;path=/;domain=' + document.domain + ';expires=' + new Date(0).toUTCString();//清除当前域名下的，例如 .m.kevis.com
            document.cookie = keys[i] + '=0;path=/;domain=kevis.com;expires=' + new Date(0).toUTCString();//清除一级域名下的或指定的，例如 .kevis.com
        }
    }
}

//获取浏览器中的cookie
let getUserCookie = (profile) => {
    if (document.cookie.length > 0) {
        // 通过分号(;)作为分割符cookie字符串
        let arr = document.cookie.split(";");
        for (let index = 0; index < arr.length; index++) {
            let items = arr[index].split("=");
            if (items.length > 2) {
                let temp = arr[index].split(items[1])
                items[1] = items[1] + temp[1];
            }
            if (items[0].replace(/\s*/g, "") === "userid") {
                profile.userid = items[1]
            } else if (items[0].replace(/\s*/g, "") === "userImg") {
                profile.userImg = items[1]
            } else if (items[0].replace(/\s*/g, "") === "name") {
                profile.name = items[1]
            } else if (items[0].replace(/\s*/g, "") === "username") {
                profile.username = items[1]
            } else if (items[0].replace(/\s*/g, "") === "userEmail") {
                profile.userEmail = items[1]
            } else if (items[0].replace(/\s*/g, "") === "userTel") {
                profile.userTel = items[1]
            } else if (items[0].replace(/\s*/g, "") === "userRole") {
                profile.userRole = items[1]
            }
        }
    }
}

/**
 * 根据token获取用户信息
 * @param token
 */
let queryUserByToken = (token) => {
    axios({
        url: '/noteUser/queryUserByToken/' + token,
    }).then(response => {
        store.commit("setUserContext",response.data)
    })
}

//获取浏览器中的Token
let getToken = (token) => {
    if (document.cookie.length > 0) {
        // 通过分号(;)作为分割符cookie字符串
        let arr = document.cookie.split(";");
        for (let index = 0; index < arr.length; index++) {
            let items = arr[index].split("=");
            if (items.length > 2) {
                let temp = arr[index].split(items[1])
                items[1] = items[1] + temp[1];
            }
            if (items[0].replace(/\s*/g, "") === "token") {
                token = items[1]
            }
        }
    }
}


export default {checkISLogin, clearCookie, getUserCookie, queryUserByToken,getToken}

